<?php

namespace backend\controllers;

use common\models\VideoType;
use common\models\VideoUser;
use Yii;
use common\models\Video;
use common\models\VideoSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * VideoController implements the CRUD actions for Video model.
 */
class VideoController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Video models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new VideoSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Video model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Video model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $userInfo = Yii::$app->user->Identity;
        $model = new Video();
        //准备分类数据
        $pids = VideoType::find()->select('id,name,pid')->asArray()->all();
        if (isset($pids) && !empty($pids)){
            $data = VideoType::getHighestLevel($pids);
        }else{
            $data = [];
        }

        if (Yii::$app->request->post()) {
            //封面图片
            $dir = Yii::getAlias('@backend').'/web/video/';
            $baseName = $_FILES['Video']['name']['cover_img'];
            $extension = $_FILES['Video']['tmp_name']['cover_img'];
            $fileName = $dir.$baseName;
            move_uploaded_file($extension,$fileName);

            $data = Yii::$app->request->post();
            $video_data = $data['Video'];
            $model->user_id = $userInfo->id;
            $model->video_title = $video_data['video_title'];
            $model->video_name = $video_data['video_name'];
            $model->description = $video_data['description'];
            $model->type = $data['pid'];
            $model->cover_img = $baseName;
            if ($model->save(false)) {
                $img_ids = $data['video_id'];
                if (!empty($img_ids)) {
                    foreach ($img_ids as $img_id) {
                        $img = VideoUser::findOne($img_id);
                        $img->video_id = $model->attributes['id'];
                        $img->save(false);
                    }
                }
                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            return $this->render('create', [
                'videoAll' => '',
                'model' => $model,
                'videoId' => "",
                'pids' => $data
            ]);
        }
    }

    /**
     * Updates an existing Video model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {

        //准备分类数据
        $pids = VideoType::find()->select('id,name,pid')->asArray()->all();
        if (isset($pids) && !empty($pids)){
            $data = VideoType::getHighestLevel($pids);
        }else{
            $data = [];
        }

        $model = $this->findModel($id);
        $videos = VideoUser::find()->select('video_url,id')->where(['video_id' => $id])->asArray()->all();
//        echo "<pre/>";
//        var_dump($videos);die;
        //获取预览数据
        foreach ($videos as $video) {
            $url = $video['video_url'];
            $videoAll[] = Yii::$app->params['video'] . $url;
            $videoId[] = ['key' => $video['id']];
//            echo "<pre/>";
//            var_dump($imgae);
        }
        if (Yii::$app->request->isPost){
            //封面图片
            $dir = Yii::getAlias('@backend').'/web/video/';
            $baseName = $_FILES['Video']['name']['cover_img'];
            $extension = $_FILES['Video']['tmp_name']['cover_img'];
            $fileName = $dir.$baseName;
            move_uploaded_file($extension,$fileName);

            $data = Yii::$app->request->post();
            $video_data = $data['Video'];
            $model->video_title = $video_data['video_title'];
            $model->video_name = $video_data['video_name'];
            $model->description = $video_data['description'];
            $model->type = $data['pid'];
            $model->cover_img = $baseName;
            if ($model->save(false)){
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }
        return $this->render('update', [
            'model' => $model,
            'videoAll' => $videoAll,
            'videoId' => $videoId,
            'data' => $data
        ]);
    }

    /**
     * Deletes an existing Video model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Video model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Video the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Video::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     *    文件上传
     *  我们这里上传成功后把图片的id进行返回
     */
    public function actionUpload ()
    {
        $model = new VideoUser();
        if (Yii::$app->request->isPost) {

            //文件上传存放的目录
            $dir = Yii::getAlias('@backend').'/web/video/';
            $baseName = $_FILES['Video']['name']['video_url'];
            $extension = $_FILES['Video']['tmp_name']['video_url'];
            if ($model->validate()) {
                //文件名
                $fileName = $dir.$baseName;
                $results = move_uploaded_file($extension,$fileName);
                if ($results){
                    $model->video_url = $baseName;
                    if ($model->save()){
                        return $model->attributes['id'];
                    }
                }
            }
        }
        return "什么玩意";
    }


}
